package com.bingxu.flink.chapter01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @author :BingXu
 * @description :TODO
 * @date :2021/8/6 11:54
 * @modifier :
 */

public class FlinkBatchWCDemo {
    public static void main(String[] args) throws Exception {
        // 获取执行环境
        ExecutionEnvironment executionEnvironment = ExecutionEnvironment.getExecutionEnvironment();

        // 获取数据
        DataSource<String> lines = executionEnvironment.readTextFile("D:\\Source\\JavaProject\\flinkdemo\\input\\words.txt");

        UnsortedGrouping<Tuple2<String, Integer>> groupByData = lines.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                // split input element
                String[] words = s.split(" ");
                for (String word : words) {
                    // output element
                    collector.collect(Tuple2.of(word, 1));
                }
            }
        }).groupBy(0);

        // 输出结果
        groupByData.sum(1).print();

    }
}
